package com.oa.common.mybatis.id;

import com.oa.common.identity.IdGenerateUtils;
import com.oa.common.identity.LocalSownFlakeIdGen;
import lombok.Synchronized;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import javax.swing.plaf.synth.SynthCheckBoxMenuItemUI;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;


/**
 * Id生成拦截器
 * 拦截 org.apache.ibatis.executor.Executor(MappedStatement, Object) 方法
 *
 * @author cuichao
 */

@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class})})
public class IdGenInterceptor implements Interceptor {

    private final String emptyKey = null;

    private final LocalSownFlakeIdGen idGen = new LocalSownFlakeIdGen();

    private final ConcurrentHashMap<Class, ClassFieldCache> cache = new ConcurrentHashMap<>(256);


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        boolean isUpdate = args.length == 2 && ms.getSqlCommandType() == SqlCommandType.INSERT;

        if (isUpdate && args[1] != null) {
            Object target = args[1];
            Class targetClass = args[1].getClass();
            //是否基础类
            if(targetClass.isPrimitive()){
                return invocation.proceed();
            }
            ClassFieldCache cache = getCache(targetClass, target);
            if (cache.isGen && cache.fields != null && cache.fields.length > 0) {
                for (Field field : cache.fields) {
                    field.setAccessible(true);
                    Long id = idGen.getId(emptyKey);
                    field.setLong(args[1], id);
                }
            }
        }
        return invocation.proceed();
    }


    private ClassFieldCache getCache(Class targetClass, Object target) {

        ClassFieldCache fieldCache = cache.getOrDefault(target, null);
        if (fieldCache != null) {
            return fieldCache;
        } else {
            synchronized (targetClass) {
                if (cache.getOrDefault(targetClass, null) != null) {
                    return cache.get(targetClass);
                } else {
                    fieldCache = createFieldCache(targetClass);
                    cache.put(targetClass, fieldCache);
                    return fieldCache;
                }
            }
        }

    }

    private ClassFieldCache createFieldCache(Class target) {
        Field[] fields = target.getFields();
        List<Field> inject = new ArrayList<>();

        for (Field field : fields) {
            IdGen annotation = field.getAnnotation(IdGen.class);
            if (annotation != null) {
                inject.add(field);
            }
        }
        boolean isCache = false;
        if (!inject.isEmpty()) {
            isCache = true;
        }
        return new ClassFieldCache(target, isCache, inject.toArray(new Field[inject.size()]));
    }


    /**
     * class对象字段缓存
     *
     * @author cuichao
     */
    private class ClassFieldCache {
        /**
         * 目标类
         */
        private Class target;
        /**
         * 该类是否需要生成ID
         */
        private boolean isGen;
        /**
         * 需要生成ID的字段
         */
        private Field[] fields;

        public ClassFieldCache() {

        }

        public ClassFieldCache(Class target, boolean isGen, Field[] fields) {
            this.target = target;
            this.isGen = isGen;
            this.fields = fields;
        }
    }


}
